<template>
  <div class="enter_voice">
    <div :class="['voice_time', { show: recordState }]">
      <div class="lines_box">
        <div class="lines first" :class="[{ active: recorder && recorder.duration.toFixed(0) % 4 > 2 }]"></div>
        <div class="lines second" :class="[{ active: recorder && recorder.duration.toFixed(0) % 4 > 1 }]"></div>
        <div class="lines third" :class="[{ active: recorder && recorder.duration.toFixed(0) % 4 > 0 }]"></div>
      </div>
      <div class="time">{{ recorder && recorder.duration.toFixed(2) }}″</div>
      <div class="lines_box">
        <div class="lines third" :class="[{ active: recorder && recorder.duration.toFixed(0) % 4 > 0 }]"></div>
        <div class="lines second" :class="[{ active: recorder && recorder.duration.toFixed(0) % 4 > 1 }]"></div>
        <div class="lines first" :class="[{ active: recorder && recorder.duration.toFixed(0) % 4 > 2 }]"></div>
      </div>
    </div>
    <div :class="['voice_content', { record_state: recordState }]" @click="onClick">
      <img src="../assets/images/common/luyin2.png" class="voice_icon" v-if="recordState" />
      <img src="../assets/images/common/luyin.png" class="voice_icon" v-else />
    </div>
    <div class="voice_tip">
      {{ recordState ? '结束录音' : '点击录音' }}
    </div>
  </div>
</template>

<script>
import Recorder from 'js-audio-recorder'
import { uploadFiles } from '@api/api.js'
import { mapState, mapMutations } from 'vuex'
import IatRecorder from '@api/xf/IatRecorder.js'
// const iatRecorder = new IatRecorder('en_us', 'mandarin', '5f27b6a9') //
export default {
  name: 'VoiceBtn',
  components: { Recorder },
  props: {},
  data() {
    return {
      recordState: false, //录音状态
      // 新录音组件
      recorder: null,
      iatRecorder: null,
      setInt: null,
      timeNum: 60,
      resultText: '',
    }
  },
  computed: {
    ...mapState(['isRecordIng']),
  },
  watch: {},
  created() {},
  mounted() {
    // document.addEventListener('visibilitychange', this.handleVisiable)
  },
  methods: {
    ...mapMutations(['setIsRecordIng']),
    onClick() {
      if (this.isRecordIng && !this.recordState) {
        this.$toast.fail('请先关闭其他录音')
        return false
      }
      if (!this.recordState) {
        // 开始录音
        this.startRecord()
      } else {
        // 结束录音
        this.$toast.loading({
          message: '录音保存中',
          forbidClick: true,
        })
        this.iatRecorder.stop()
        this.recordState = false
      }
    },
    startRecord() {
      let that = this
      Recorder.getPermission().then(
        () => {
          that.iatRecorder = new IatRecorder('en_us', 'mandarin', '5f27b6a9') //
          that.iatRecorder.start()
          that.iatRecorder.onWillStatusChange = (oldStatus, status) => {
            let time = 0
            if (status === 'ing') {
              // 链接成功
              that.setInt = setInterval(() => {
                time++
                if (time >= 55) {
                  this.$toast.loading({
                    duration: 0, // 持续展示 this.$toast
                    message: `倒计时 ${that.timeNum - time} 秒`,
                  })
                }
                if (time >= that.timeNum - 1) {
                  this.$toast.clear()
                  that.iatRecorder.stop()
                  clearInterval(this.setInt)
                }
              }, 1000)
              that.recorder = new Recorder({ type: 'mp3', bitRate: 8, sampleRate: 8000 })
              that.recorder.start() // 开始录音
              that.recordState = true
              that.setIsRecordIng(true)
            } else if (status === 'end') {
              clearInterval(this.setInt)
            }
          }
          that.iatRecorder.onTextChange = function (text) {
            that.resultText = text
          }
          that.iatRecorder.OnRecognitionComplete = () => {
            that.endRecorder()
          }
        },
        error => {
          console.log(`${error.name} : ${error.message}`)
        }
      )
    },
    endRecorder() {
      this.recordState = false
      this.setIsRecordIng(false)
      this.$toast.clear()
      clearInterval(this.setInt)
      this.recorder.stop()
      if (this.recorder == null || this.recorder.duration < 1) {
        return false
      }
      // 上传保存录音文件
      var formData = new FormData()
      var blob = this.recorder.getWAVBlob()
      var newbolb = new Blob([blob], { type: 'audio/mp3' })
      var fileOfBlob = new File([newbolb], new Date().getTime() + '.mp3')
      formData.append('files', fileOfBlob)
      uploadFiles(formData)
        .then(res => {
          let resData = {}
          resData.audioList = res.data[0]
          resData.audioList.duration = this.recorder.duration.toFixed(0)
          resData.entryCont = this.resultText
          this.$emit('recordend', JSON.stringify(resData))
          this.resultText = ''
          this.recorder.destroy()
        })
        .catch(err => {
          this.recorder.destroy()
        })
    },
    handleVisiable(e) {
      // 用户离开了当前页面
      if (e.target.visibilityState === 'hidden') {
        console.log('页面不可见')
      }
      // 用户打开或回到页面
      if (e.target.visibilityState === 'visible') {
        document.title = '页面可见'
        console.log('页面可见')
      }
    },
  },
  beforeDestroy() {
    if (this.destroy) {
      this.recorder.destroy()
    }
    if (this.setInt) {
      clearInterval(this.setInt)
    }
    if (this.iatRecorder) {
      this.iatRecorder.stop()
    }
    this.setIsRecordIng(false)
  },
}
</script>

<style lang="scss" scoped>
.enter_voice {
  width: calc(100% - 4px);
  height: calc(100% - 4px);
  background-color: #f9f9f9;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: center;
  margin: 2px;
  padding: 5px 0 10px;
  .voice_time {
    margin-bottom: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 12px;
    opacity: 0;

    &.show {
      opacity: 1;
    }
    .time {
      font-size: 12px;
      color: #666666;
      margin: 0 3px 0 5px;
    }

    .lines_box {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;

      .lines {
        background-color: #e6e6e6;
        width: 2px;
        margin-left: 3px;
        border-radius: 1px;

        &.active {
          background-color: #d80a06;
        }

        &.first {
          height: 50%;
        }

        &.second {
          height: 80%;
        }

        &.third {
          height: 100%;
        }
      }
    }
  }

  .voice_content {
    height: 60px;
    width: 60px;
    border-radius: 50%;
    background-color: #ffffff;
    display: flex;
    justify-content: center;
    align-items: center;
    box-shadow: 0 0 10px 0 rgba(4, 0, 0, 0.15);
    &.record_state {
      background-color: #f9f9f9;
    }

    .voice_icon {
      width: 29px;
    }
  }

  .voice_tip {
    font-size: 13px;
    color: #333333;
    margin-top: 4px;
    padding-top: 2px;
  }
}
</style>
